// pages/box-detail/box-detail.js
import Toast from '@vant/weapp/toast/toast';
import {
  HTTP
} from '../../utils/http'
import {
  formatDate
} from '../../utils/util'
let http = new HTTP();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    myReferencePictureShow: false,
    viewNameShow: false,
    editShow: false,
    moreShow: false,
    show: false,
    closeSrc: '/images/icon/close.png',
    autosize: {
      maxHeight: '686rpx',
      minHeight: '524rpx'
    },
    value: '',
    // 是否已经生成
    isBuild: false,
    // 是否已收藏表情
    isCollectExpress: false,
    boxId: '',
    boxDetail: {},
    nameTemp: "",
    boxRelationList: [],
    buildData: {},
    pictureStyleList: [],
    userInfo: {}
  },
  onEditImage() {
    this.setData({
      myReferencePictureShow: true
    })
  },
  onEditName() {
    this.setData({
      viewNameShow: true
    })
  },
  //临时名称
  onChangeTempName(e) {
    this.setData({
      nameTemp: e.detail
    })
  },
  onDoneEditName() {
    http.request({
      url: '/ai/draw/box/update',
      method: 'post',
      data: {
        id: this.data.boxDetail.id,
        name: this.data.nameTemp
      },
      success: (res) => {
        if (res.code === "0") {
          this.setData({
            "boxDetail.name": this.data.nameTemp
          })
        }
      }
    })
  },

  onDelete() {
    http.request({
      url: '/ai/draw/box/delete',
      data: {
        id: this.data.boxDetail.id
      },
      success: (res) => {
        // 删除完成后跳转到首页
        wx.reLaunch({
          url: "/pages/home/home"
        })
      }
    })
  },

  onIsPrivate(e) {
    http.request({
      url: '/ai/draw/box/update',
      method: "POST",
      data: {
        id: this.data.boxDetail.id,
        isPrivate: e.currentTarget.dataset.value
      },
      success: (res) => {
        this.getBoxDetail(this.data.boxDetail.id)
      }
    })
  },

  onLock(e) {
    http.request({
      url: '/ai/draw/box/update',
      method: "POST",
      data: {
        id: this.data.boxDetail.id,
        isParamLock: e.currentTarget.dataset.value
      },
      success: (res) => {
        this.getBoxDetail(this.data.boxDetail.id)
      }
    })
  },

  onReferencePictureClose(e) {
    if (e.detail && e.detail !== this.data.boxDetail.url) {
      http.request({
        url: '/ai/draw/box/update',
        method: "POST",
        data: {
          id: this.data.boxDetail.id,
          url: e.detail
        },
        success: (res) => {
          if (res.code === '0') {
            this.setData({
              "boxDetail.url": e.detail
            })
          }
        }
      })
    } else {

    }
  },

  onMore() {
    this.setData({
      moreShow: true
    })
  },
  onMoreClose() {
    this.setData({
      moreShow: false
    });
  },

  onEdit() {
    this.setData({
      moreShow: false,
      editShow: true
    })
  },
  onEditClose() {
    this.setData({
      editShow: false
    });
  },
  onDownFile() {
    let url = this.data.boxDetail.url
    let that = this
    //若二维码未加载完毕，加个动画提高用户体验
    wx.showToast({
      icon: 'loading',
      title: '正在保存图片',
      duration: 1000
    })
    //判断用户是否授权"保存到相册"
    wx.getSetting({
      success(res) {
        //没有权限，发起授权
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() { //用户允许授权，保存图片到相册
              that.savePhoto(url);
            },
            fail() { //用户点击拒绝授权，跳转到设置页，引导用户授权
              wx.openSetting({
                success() {
                  wx.authorize({
                    scope: 'scope.writePhotosAlbum',
                    success() {
                      that.savePhoto(url);
                    }
                  })
                }
              })
            }
          })
        } else { //用户已授权，保存到相册
          that.savePhoto(url)
        }
      }
    })
  },
  //保存图片到相册，提示保存成功
  savePhoto(url) {
    let that = this
    wx.downloadFile({
      url: url,
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(res) {
            wx.showToast({
              title: '保存成功',
              icon: "success",
              duration: 1000
            })
          }
        })
      }
    })
  },

  onClose() {
    this.setData({
      show: false
    });
  },

  collectBoxTap() {
    const boxId = this.data.boxId;
    if (this.data.boxDetail.isCollect) {
      http.request({
        url: '/ai/draw/box/cancel/collect',
        data: {
          boxId: boxId
        },
        success: (res) => {
          if (res.code === "0") {
            this.getBoxDetail(boxId);
          }
        }
      })
    } else {
      http.request({
        url: '/ai/draw/box/collect',
        method: 'post',
        data: {
          boxId: boxId
        },
        success: (res) => {
          if (res.code === "0") {
            // this.setData({
            //   'boxDetail.isCollect': true,
            // })
            this.getBoxDetail(boxId);
          }
        }
      })
    }
  },

  collectExpressTap() {
    Toast({
      message: '收藏成功',
      position: 'top'
    });
    this.setData({
      isCollectExpress: !this.data.isCollectExpress
    })
  },

  onTapCreate() {
    wx.navigateTo({
      url: '/pages/creationWork/creationWork?boxId=' + this.data.boxId,
    })
    // this.setData({
    //   "buildData.description": null,
    //   isBuild: false
    // })
    // this.setData({
    //   show: true
    // })
  },

  descriptionChange(e) {
    this.setData({
      "buildData.description": e.detail
    })
  },

  // 开始生成
  onStartTap() {
    http.request({
      url: '/ai/draw/picture/build',
      data: {
        boxId: this.data.boxId,
        description: this.data.buildData.description
      },
      success: (res) => {
        if (res.code === "0") {
          this.setData({
            "buildData.imgSrc": res.data,
          })
        }
      }
    })
    this.setData({
      isBuild: true
    })
  },

  /**
   * 最终生成
   */
  finish() {
    http.request({
      url: '/ai/draw/picture/create/finish',
      method: "POST",
      data: {
        "url": this.data.buildData.imgSrc,
        "boxId": this.data.boxId,
        "description": this.data.buildData.description
      },
      success: (res) => {
        if (res.code === "0") {
          this.setData({
            show: false,
          })
          this.getBoxRelationList(this.data.boxId)
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      boxId: options.id
    })
    this.getBoxDetail(options.id);
    this.getBoxRelationList(options.id)
  },

  getBoxDetail(boxId) {
    http.request({
      url: '/ai/draw/box/detail',
      data: {
        id: boxId
      },
      success: (res) => {
        if (res.code === "0") {
          let createAt = formatDate(res.data.createAt)
          res.data.createAt = createAt
          let styleId = res.data.styleId
          let styleName
          this.data.pictureStyleList.forEach(item => {
            if (styleId === item.id) {
              styleName = item.chinese
              return true;
            }
          });
          res.data.styleName = styleName
          this.setData({
            boxDetail: res.data,
          })
        }
      }
    })
  },

  focusTap() {
    http.request({
      url: '/ai/draw/account/focus/account',
      data: {
        focusedAccountId: this.data.boxDetail.accountInfo.id
      },
      success: (res) => {
        if (res.code === "0") {
          this.getBoxDetail(this.data.boxDetail.id);
        }
      }
    })
  },

  cancelFocusTap() {
    http.request({
      url: '/ai/draw/account/cancel/focus/account',
      data: {
        focusedAccountId: this.data.boxDetail.accountInfo.id
      },
      success: (res) => {
        if (res.code === "0") {
          this.getBoxDetail(this.data.boxDetail.id);
        }
      }
    })
  },

  /**
   * 获取风格字典
   */
  styleDict() {
    http.request({
      url: '/ai/draw/dict/get/list',
      method: "GET",
      data: {
        type: 0
      },
      success: (res) => {
        let data = res.data;
        this.setData({
          pictureStyleList: data
        })
      }
    })
  },

  /**
   * 查询创作盒历史表情
   */
  getBoxRelationList(boxId) {
    http.request({
      url: '/ai/draw/picture/get/box/page/history',
      method: "POST",
      data: {
        "pageSize": 100,
        "pageNum": 1,
        "boxId": boxId
      },
      success: (res) => {
        if (res.code === "0") {
          this.setData({
            boxRelationList: res.data.list,
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.styleDict()
    let _this = this
    wx.getStorage({
      key: 'userId',
      success: function (res) {
        _this.setData({
          "userInfo.id": res.data
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(e) {
  }
})